// 管理日志
import { useQuery } from '@tanstack/react-query';
import type { ColumnType } from 'antd/lib/table';
import dayjs from 'dayjs';
import { useEffect, useState } from 'react';

import api from '@/apis/api';
import CustomTable from '@/components/CustomTable';
import Filter from '@/components/FilterTop';

import styles from './styles.module.less';

type TableData = {
  id: number;
  grant: number;
  created_at: string;
  message: string;
  level: number;
};

export default function ManageLog() {
  const [, setKeyword] = useState<string>();

  // 记录总数
  const [total, setTotal] = useState<number>(0);
  // 记录页码
  const [page, setPage] = useState<number>(1);
  const [pageSize, setPageSize] = useState<number>(10);

  const [ManageLogTable, setManageLogTable] = useState<TableData[]>([]);

  const columns: (ColumnType<TableData> & { align?: 'left' | 'right' | 'center' })[] = [
    {
      title: '序号',
      dataIndex: 'id',
      key: 'id',
      width: 150,
      align: 'center',
    },
    {
      title: '用户类型',
      dataIndex: 'grant',
      key: 'grant',
      width: 290,
      align: 'center',
      render: (text) => {
        return text === 0 ? '管理员' : '操作员';
      },
    },
    {
      title: '时间',
      dataIndex: 'created_at',
      key: 'created_at',
      width: 320,
      align: 'center',
      render: (data) => {
        const d = data ? dayjs(data).format('YYYY-MM-DD HH:mm:ss') : '';
        return d;
      },
    },
    {
      title: '信息',
      dataIndex: 'message',
      key: 'message',
      width: 380,
      align: 'center',
    },
    {
      title: '等级',
      dataIndex: 'level',
      key: 'level',
      width: 200,
      align: 'center',
      render: (text) => {
        return text === 0 ? '正常' : '错误';
      },
    },
  ];

  const { data: ManageLogData } = useQuery({
    queryKey: ['getManageLog', { page, pageSize }],
    queryFn: async () => {
      const res: any = await api.GetLogData({
        log_type: 0,
        skip: (page - 1) * pageSize,
        take: pageSize,
      });
      return res.data;
    },
  });

  useEffect(() => {
    if (ManageLogData) {
      setTotal(ManageLogData.total);
      setManageLogTable(ManageLogData.items);
    }
  }, [ManageLogData]);

  return (
    <>
      {/* 关键字搜索框 */}
      <Filter setKeyword={setKeyword} typeName={'manage-log'} />
      {/* 日志列表显示 */}
      <div
        className={styles.Table}
        style={{
          background: '#fff',
          padding: '25px',
          marginBottom: '25px',
          marginTop: '18px',
        }}
      >
        <CustomTable
          total={total}
          page={page}
          pageSize={pageSize}
          setPage={setPage}
          setPageSize={setPageSize}
          dataSource={ManageLogTable}
          columns={columns}
          rowClassName={(_record, index) => (index % 2 === 0 ? 'even-row' : 'odd-row')}
          scroll={{ x: 800, y: 800 }}
          rowKey="id"
        />
      </div>
    </>
  );
}
